package com.jt.interceptor;
//MVC权限拦截器

import com.jt.pojo.User;
import com.jt.util.ObjectMapperUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import redis.clients.jedis.JedisCluster;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//HandlerInterceptor 对外提供的拦截器接口
@Component
public class UserInterceptor implements HandlerInterceptor {

    @Autowired
    private JedisCluster jedisCluster;

    /**
     * 目的:如果用户不登陆,则不允许访问权限相关业务
     * 返回值; true:表示放行,
     * false:表示拦截
     * 注意事项:  必须添加拦截器策略
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception 业务说明:
     *                   1.如果已经登录,放行,否则拦截
     *                   如何判断用户是否登录
     *                   1.判断客户端是否有指定的Cookie
     *                   2.应该获取cookie中的值,去redis中校验 是否存在,true
     *                   如果上面都满足,放行
     */

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
        //1.获取cookie
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                if ("JT_TICKET".equals(cookie.getName())) {
                    String ticket = cookie.getValue();
                    if (jedisCluster.exists(ticket)) {

                        //3.动态存取userId
                        String userJSON = jedisCluster.get(ticket);
                        User user = ObjectMapperUtil.toObject(userJSON, User.class);
                        request.setAttribute("JT_USER", user);
                        return true;
                    }
                }
            }
        }
        //重定向到用户登录页面
        response.sendRedirect("/user/login.html");
        return false;

    }
}
